package models

import (
	"fly/schema"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysRoleMenu struct {
	BaseModel
	RoleId int64 `orm:"column(role_id);description(角色ID)"`
	MenuId int64 `orm:"column(menu_id);description(菜单ID)"`
}

func init() {
	orm.RegisterModel(new(SysRoleMenu))
}

// SearchField 定义模型的可搜索字段
func (*SysRoleMenu) SearchField() []string {
	return []string{"role_id", "menu_id"}
}

// WhereField 定义模型可作为条件的字段
func (*SysRoleMenu) WhereField() []string {
	return []string{"id", "status", "role_id", "menu_id"}
}

func (m *SysRoleMenu) TableName() string {
	return "sys_role_menu"
}

// AddSysRoleMenu insert a new SysRoleMenu into database and returns
// last inserted Id on success.
func AddSysRoleMenu(m *SysRoleMenu, userId int64) (id int64, err error) {
	o := orm.NewOrm()
	m.Creator = userId
	m.Updater = userId
	id, err = o.Insert(m)
	return
}

// GetSysRoleMenuById retrieves SysRoleMenu by Id. Returns error if
// Id doesn't exist
func GetSysRoleMenuById(id int64) (v *SysRoleMenu, err error) {
	o := orm.NewOrm()
	v = &SysRoleMenu{BaseModel: BaseModel{Id: id}}
	if err = o.QueryTable(new(SysRoleMenu)).Filter("id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateSysRoleMenuById updates SysRoleMenu by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysRoleMenuById(m *SysRoleMenu, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleMenu{BaseModel: BaseModel{Id: m.Id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Updater = userId
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysRoleMenu deletes SysRoleMenu by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysRoleMenu(id int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleMenu{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysRoleMenu{BaseModel: BaseModel{Id: id}}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// DestroySysRoleMenu Destroy SysRoleMenu by Id and returns error
func DestroySysRoleMenu(id int64, userId int64) (err error) {
	o := orm.NewOrm()
	v := SysRoleMenu{BaseModel: BaseModel{Id: id}}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		v.Status = schema.StatusDelete
		v.Updater = userId
		var num int64
		if num, err = o.Update(v, "updater", "status"); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
